package com.feng.zhihao.apigeteway.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.feng.zhihao.apigeteway.entity.UserInfo;

@Controller
@RequestMapping("/")
public class Home {
	
	@RequestMapping("index.do")
	public String index(Model model,HttpServletRequest request,HttpServletResponse response) {
		return "hello";
	}

	@RequestMapping("home.do")
	public String home(Model model) {
		return null;
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String loginForm(Model model,HttpServletRequest request,HttpServletResponse response) {
		return "login";
		
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(@Valid UserInfo userInfo, BindingResult bindingResult, RedirectAttributes redirectAttributes,HttpServletRequest request,HttpServletResponse response) {
		if (bindingResult.hasErrors()) {
			return "redirect:/login";
		}
		UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getUserId(), userInfo.getPassword());
		org.apache.shiro.subject.Subject currentUser = SecurityUtils.getSubject();
		try {
			currentUser.login(token);			
		} catch (UnknownAccountException e) {
            redirectAttributes.addFlashAttribute("message", "账号不存在");			
		} catch (IncorrectCredentialsException e) {
			redirectAttributes.addFlashAttribute("message", "密码错误");
		} 
		//验证是否登录成功  
        if(currentUser.isAuthenticated()){
        	request.getSession().setAttribute("currentUser", currentUser.getPrincipal());
            return "redirect:/index.do";
        }else{  
            token.clear();  
            return "redirect:/login";
        }
	}
}
